package main

import (
	"time"

	"github.com/lxn/walk"
)

type labelGroup struct {
	Label string   `json:"label"`
	Names []string `json:"names"`
}

type nameSheet struct {
	Sheet       string       `json:"sheet"`
	LabelGroups []labelGroup `json:"labelGroups"`
}

type config struct {
	NameSheets    []nameSheet   `json:"nameSheets"`
	Groups        int           `json:"groups"`
	Nums          int           `json:"nums"`
	Animate       bool          `json:"animate"`
	UseTTS        bool          `json:"useTTS"`
	Timer         time.Duration `json:"timer"`
	Timeout       time.Duration `json:"timeout"`
	SelectedSheet int           `json:"selectedSheet"`
	Repeat        bool          `json:"repeat"`
}

var c *config

func (cfg *config) GetSheet(sheetName string) int {
	for i, v := range cfg.NameSheets {
		if v.Sheet == sheetName {
			return i
		}
	}
	cfg.NameSheets = append(cfg.NameSheets, nameSheet{
		Sheet:       sheetName,
		LabelGroups: []labelGroup{},
	})
	return len(cfg.NameSheets) - 1
}

func (cfg *config) GetGroup(sheetIndex int, labelName string) int {
	for i, v := range cfg.NameSheets[sheetIndex].LabelGroups {
		if v.Label == labelName {
			return i
		}
	}
	cfg.NameSheets[sheetIndex].LabelGroups = append(
		cfg.NameSheets[sheetIndex].LabelGroups,
		labelGroup{
			Label: labelName,
			Names: []string{},
		},
	)
	return len(cfg.NameSheets[sheetIndex].LabelGroups) - 1
}

func (cfg *nameSheet) checkNameExist(name string) bool {
	for _, i := range cfg.LabelGroups {
		for _, v := range i.Names {
			if v == name {
				return true
			}
		}
	}
	return false
}

// 检测异常并抛出
func ifErr(err error) {
	if err != nil {
		// 希望永远也不要执行
		walk.MsgBox(nil, "错误", "程序发生致命异常退出，请重新启动\n"+err.Error(), walk.MsgBoxIconError)
		panic(err)
	}
}
